package com.acme;

import java.io.Serializable;
import java.util.Formatter;

public class Bank implements Serializable {
	
	private final Client[] clients = new Client[10];
	private int maxClients = 0;
	private ClientRegistrationListener[] listeners;
	
	class PrintClientListener implements ClientRegistrationListener {
		public void onClientAdded(Client client) {
			System.out.println(client.getName() + " has been added");
		}
	}
	
	class EmailNotificationListener implements ClientRegistrationListener {
		public void onClientAdded(Client client) {
			Formatter fmt = new Formatter();
			System.out.println(fmt.format("Notification email for client %s to be sent", client.getName()));
			fmt.close();
			
			Email email = new Email();
			email.setMessage("Hi!");
			try {
				new EmailService().sendMail(email);
			}
			catch(Exception ex) { System.out.println("The email hasn't been sent!"); }
		}
	}

	public Bank() {
		this.listeners = new ClientRegistrationListener[2];
		listeners[0] = new PrintClientListener();
		listeners[1] = new EmailNotificationListener();
	}
	
	public Bank(ClientRegistrationListener[] listeners) {
		int length = listeners.length;
		this.listeners = new ClientRegistrationListener[length];
		for(int i = 0; i < length; i++) {
			this.listeners[i] = listeners[i];
		}
	}

	public Client addClient(final Client client) {
		clients[maxClients++] = client;
		
		for(ClientRegistrationListener listener: listeners) {
			listener.onClientAdded(client);
		}
		return client;
	}
}